<template>
  <div class="activity-management">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>活动管理 /</span>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="openCreateModal">+ 创建活动</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="渠道来源：">
          <el-select v-model="searchForm.channel" placeholder="请选择" clearable style="width: 180px;">
            <el-option label="线上活动" :value="'1'"></el-option>
            <el-option label="推广介绍" :value="'2'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动类型：">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 180px;">
            <el-option label="课程折扣" :value="'1'"></el-option>
            <el-option label="代金券" :value="'2'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动状态：">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 180px;">
            <el-option label="未开始" :value="'1'"></el-option>
            <el-option label="进行中" :value="'2'"></el-option>
            <el-option label="已结束" :value="'3'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="activitiesData" style="width: 100%" height="calc(100vh - 400px)">
        <el-table-column prop="id" label="序号" width="80"></el-table-column>
        <el-table-column prop="name" label="活动名称"></el-table-column>
        <el-table-column prop="channel" label="渠道来源" width="120">
          <template #default="scope">
            {{ getChannelName(scope.row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="活动明细" width="150">
          <template #default="scope">
            <div v-if="scope.row.type === 1">
              {{ scope.row.discount }}折
            </div>
            <div v-else>
              {{ scope.row.voucher }}元
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间"></el-table-column>
        <el-table-column prop="endTime" label="结束时间"></el-table-column>
        <el-table-column prop="status" label="活动状态" width="120">
          <template #default="scope">
            {{ getStatusName(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openEditModal(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="deleteActivity(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑活动模态框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="closeDialog"
    >
      <el-form :model="activityForm" :rules="rules" ref="activityFormRef" label-width="120px">
        <el-form-item label="渠道来源：" prop="channel">
          <el-select v-model="activityForm.channel" placeholder="请选择" clearable>
            <el-option label="线上活动" value="1"></el-option>
            <el-option label="推广介绍" value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动名称：" prop="name">
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item label="活动日期：" prop="startTime">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DDTHH:mm:ss"
            @change="handleDateChange"
          />
        </el-form-item>
        
        <el-form-item label="活动简介：" prop="description">
          <el-input v-model="activityForm.description" type="textarea" :rows="3" placeholder="请输入活动简介" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item label="活动类型：" prop="type">
          <el-select v-model="activityForm.type" placeholder="请选择" clearable @change="handleTypeChange">
            <el-option label="课程折扣" value="1"></el-option>
            <el-option label="代金券" value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="activityForm.type === '1'" label="课程折扣：" prop="discount">
          <el-input v-model.number="activityForm.discount" placeholder="请输入折扣" type="number" :min="0.1" :max="9.9" :step="0.1"></el-input>
        </el-form-item>
        
        <el-form-item v-if="activityForm.type === '2'" label="代金券：" prop="voucher">
          <el-input v-model.number="activityForm.voucher" placeholder="请输入金额" type="number" :min="1" :max="99999"></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveActivity">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useActivityStore } from '@/stores/activity';
import { getActivityList, createActivity, updateActivity, deleteActivity as deleteActivityApi } from '@/api/activity';

export default {
  name: 'ActivityView',
  setup() {
    // 初始化活动store
    const activityStore = useActivityStore();
    return { activityStore };
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        channel: '',
        type: '',
        status: ''
      },
      // 活动数据
      activitiesData: [],
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 模态框数据
      dialogVisible: false,
      dialogTitle: '创建活动',
      editingId: null,
      // 活动表单
      activityForm: {
        channel: '',
        name: '',
        startTime: '',
        endTime: '',
        description: '',
        type: '',
        discount: null,
        voucher: null
      },
      dateRange: null,
      // 表单验证规则
      rules: {
        channel: [
          { required: true, message: '请选择渠道来源', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 20, message: '活动名称长度在1-20个字符', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入活动简介', trigger: 'blur' },
          { min: 5, max: 100, message: '活动简介长度在5-100个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        discount: [
          { required: (rule, value, callback) => {
            if (this.activityForm.type === '1' && !value) {
              callback(new Error('请输入折扣'));
            } else if (value && (value < 0.1 || value > 9.9)) {
              callback(new Error('折扣范围在0.1-9.9之间'));
            } else {
              callback();
            }
          }, trigger: 'blur,change' }
        ],
        voucher: [
          { required: (rule, value, callback) => {
            if (this.activityForm.type === '2' && !value) {
              callback(new Error('请输入代金券金额'));
            } else if (value && (value < 1 || value > 99999)) {
              callback(new Error('代金券金额范围在1-99999之间'));
            } else {
              callback();
            }
          }, trigger: 'blur,change' }
        ]
      },
      // 数据映射
      channelMap: {
        '1': '线上活动',
        '2': '推广介绍'
      },
      typeMap: {
        '1': '课程折扣',
        '2': '代金券'
      },
      statusMap: {
        '1': '未开始',
        '2': '进行中',
        '3': '已结束'
      }
    };
  },
  computed: {
    // 计算属性，用于获取当前活动状态
    getActivityStatus() {
      return (startTime, endTime) => {
        const now = new Date();
        const start = new Date(startTime);
        const end = new Date(endTime);
        if (now < start) return 1; // 未开始
        if (now > end) return 3; // 已结束
        return 2; // 进行中
      };
    }
  },
  
  // 生命周期钩子
  created() {
    // 确保活动数据已初始化
    this.initializeActivityData();
  },
  
  mounted() {
    this.loadActivities();
  },
  
  methods: {
    // 获取渠道名称
    getChannelName(channelId) {
      return this.channelMap[channelId] || '未知';
    },
    
    // 获取活动类型名称
    getTypeName(typeId) {
      return this.typeMap[typeId] || '未知';
    },
    
    // 获取状态名称
    getStatusName(statusId) {
      return this.statusMap[statusId] || '未知';
    },
    
    // 初始化活动数据
    async initializeActivityData() {
      if (!this.activityStore || !this.activityStore.initialized) {
        await this.activityStore.initializeActivities();
      }
    },
    
    // 保存活动后刷新数据
    async afterSaveActivity() {
      // 保存成功后刷新活动数据
      if (this.activityStore) {
        await this.activityStore.refreshActivities();
      }
    },
    
    // 加载活动列表
    async loadActivities() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        };
        
        // 过滤掉空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key];
          }
        });
        
        const response = await getActivityList(params);
        if (response.code === 1) {
          this.activitiesData = response.data.rows || [];
          this.total = response.data.total || 0;
          
          // 计算每条数据的状态
          this.activitiesData.forEach(item => {
            item.status = this.getActivityStatus(item.startTime, item.endTime);
          });
        }
      } catch (error) {
        this.$message.error('加载活动列表失败');
      }
    },
    
    // 格式化日期时间（备用）
    formatDateTime(date) {
      if (typeof date === 'string') {
        return date;
      }
      return date.getFullYear() + '-' + 
        String(date.getMonth() + 1).padStart(2, '0') + '-' + 
        String(date.getDate()).padStart(2, '0') + ' ' + 
        String(date.getHours()).padStart(2, '0') + ':' + 
        String(date.getMinutes()).padStart(2, '0') + ':' + 
        String(date.getSeconds()).padStart(2, '0');
    },
    
    // 搜索
    search() {
      this.currentPage = 1;
      this.loadActivities();
      // 这里应该根据搜索条件重新加载数据
    },
    
    // 重置
    reset() {
      this.searchForm = {
        channel: '',
        type: '',
        status: ''
      };
      this.search();
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.loadActivities();
    },
    
    // 当前页变化
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadActivities();
    },
    
    // 打开创建模态框
    openCreateModal() {
      this.dialogTitle = '创建活动';
      this.editingId = null;
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 打开编辑模态框
    openEditModal(activity) {
      this.dialogTitle = '编辑活动';
      this.editingId = activity.id;
      // 复制活动数据到表单，并确保时间格式正确
      this.activityForm = {
        id: activity.id,
        channel: String(activity.channel),
        name: activity.name,
        startTime: activity.startTime.includes('T') ? activity.startTime : activity.startTime.replace(' ', 'T'),
        endTime: activity.endTime.includes('T') ? activity.endTime : activity.endTime.replace(' ', 'T'),
        description: activity.description,
        type: String(activity.type),
        discount: activity.discount,
        voucher: activity.voucher
      };
      // 设置日期范围，显示时需要转换回带空格的格式
      if (activity.startTime && activity.endTime) {
        this.dateRange = [
          activity.startTime.replace('T', ' '),
          activity.endTime.replace('T', ' ')
        ];
      }
      this.dialogVisible = true;
    },
    
    // 关闭对话框
    closeDialog() {
      this.dialogVisible = false;
      this.resetForm();
      if (this.$refs.activityFormRef) {
        this.$refs.activityFormRef.resetFields();
      }
    },
    
    // 重置表单
    resetForm() {
      this.activityForm = {
        channel: '',
        name: '',
        startTime: '',
        endTime: '',
        description: '',
        type: '',
        discount: '',
        voucher: ''
      };
      this.dateRange = null;
    },
    
    // 处理日期变化
    handleDateChange(range) {
      if (range && range.length === 2) {
        // 确保格式为 ISO 8601，包含 T 字符
        this.activityForm.startTime = range[0].replace(' ', 'T');
        this.activityForm.endTime = range[1].replace(' ', 'T');
      } else {
        this.activityForm.startTime = '';
        this.activityForm.endTime = '';
      }
    },
    
    // 处理活动类型变化
    handleTypeChange(type) {
      if (type === '课程折扣') {
        this.activityForm.voucher = '';
      } else {
        this.activityForm.discount = '';
      }
    },
    
    // 保存活动
    async saveActivity() {
      this.$refs.activityFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 确保时间格式包含 T 字符
            const startTime = this.activityForm.startTime.includes('T') ? 
              this.activityForm.startTime : this.activityForm.startTime.replace(' ', 'T');
            const endTime = this.activityForm.endTime.includes('T') ? 
              this.activityForm.endTime : this.activityForm.endTime.replace(' ', 'T');
              
            const formData = {
              ...this.activityForm,
              channel: Number(this.activityForm.channel),
              type: Number(this.activityForm.type),
              startTime: startTime,
              endTime: endTime
            };
            
            // 删除不需要的字段
            delete formData.status;
            
            let response;
            if (this.editingId) {
              // 更新活动
              response = await updateActivity(formData);
            } else {
              // 创建活动
              response = await createActivity(formData);
            }
            
            if (response.code === 1) {
              this.$message.success(this.editingId ? '活动更新成功' : '活动创建成功');
              this.closeDialog();
              // 刷新活动数据
              await this.afterSaveActivity();
              this.loadActivities();
            } else {
              this.$message.error(response.msg || (this.editingId ? '活动更新失败' : '活动创建失败'));
            }
          } catch (error) {
            this.$message.error('网络错误，请稍后重试');
          }
        }
      });
    },
    
    // 删除活动
    async deleteActivity(id) {
      this.$confirm('确定要删除该活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteActivityApi(id);
          if (response.code === 1) {
            this.$message.success('活动删除成功');
            // 刷新活动数据
            await this.afterSaveActivity();
            this.loadActivities();
          } else {
            this.$message.error(response.msg || '活动删除失败');
          }
        } catch (error) {
          this.$message.error('网络错误，请稍后重试');
        }
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.operation-area {
  margin-bottom: 20px;
}

.search-area {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-top: -20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格单元格居中 */
:deep(.el-table .el-table__cell) {
  text-align: center;
}
</style>